// 函数组件
import React, { useState, useEffect } from 'react';
import "../goods/css/GoodStock.less"
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { Table, Switch, Modal, message, ConfigProvider,Select } from 'antd';
import TagDialog from '../goods/child/TagDialog';
import zh_CN from 'antd/es/locale/zh_CN';
import {getListByCon,updateByStatus,deleteSku} from "../../../api/lys"
interface DataType {
    id:number
    goodsName: string
skuBarCode: string
skuGoodsId: number
skuId: number
skuImag: string
skuInterlinkage: string
skuMarketValue: number
skuMsg: string
skuPrice: number
skuPriceRange: string
skuSell: number
skuSer: string
skuStatus: string
skuStock: number
skuSuccession: string
skuUser:string
skuVido: string
skuYear: string
}

function GoodStock() {
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'skuGoodsId',
            align: 'center',
            width: '15%'
        },
        {
            title: '商品货号',
            dataIndex: 'skuId',
            align: 'center',
        },
        {
            title: '商品名称',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '商品类型',
            dataIndex: 'skuSuccession',
            align: 'center',
        },
        {
            title: '尺码',
            dataIndex: 'skuMsg',
            align: 'center',
        },
        {
            title: '条形码',
            dataIndex: 'skuBarCode',
            align: 'center',
        },
        {
            title: '库存',
            dataIndex: 'skuStock',
            align: 'center',
        },
        {
            title: '是否启用',
            dataIndex: 'checked',
            align: 'center',
            render: (_, record) => {
                return (
                    <Switch defaultChecked={record.skuStatus=="4"?true:false} 
                    // onChange={}
                   onClick={()=>switchChange(record)}
                    />
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            render: (value, record) => (
                <div>
                    <button className='del' onClick={()=>delSku(record)}>删除</button>
                </div>
            ),
        },
    ];

   


    const [page, setPage] = useState(1)
    const [pageSize, setPageSize] = useState(10)
    const [count, setCount] = useState<number>()
    const [selectedRow, setSelectedRow] = useState<number[]>([]);
    // 多选的列
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [data, setData] = useState<DataType[]>([])
    // const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    //     console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    //     setSelectedRowKeys(newSelectedRowKeys);
    // };
   
    const [sort, setSort] = useState([
        { id: 1, value: 1, label:"按库存顺序" },
        { id: 2, value: 2, label:"按库存倒序"},
      ])
      const addKey = (data: any) => {
        data.map((item:any) => {
          item.id = Math.floor(Math.random() * 10000000000)
          return item
        })
      }
     


      useEffect(() => {
        goodsList({
            "limit": pageSize,
            "page": page
          })
      }, [page, pageSize])

      const goodsList = (obj:any) => {
        getListByCon(obj).then((res) => {
          console.log("请求的数据", res.data);
          setData(res.data.skuVos)
          addKey(res.data.skuVos)
          setCount(res.data.total)
        })
      }

//单个修改状态
const switchChange = (record:any)=>{
console.log("record",record);
updateByStatus({
    "ids": [record.skuId],
    "status":`${record.skuStatus=="5"?"4":"5"}`
  }).then((res)=>{
    console.log(res.msg,res);

  })

}

      const onChangePage = (page: any, pageSize: any) => {
        console.log("页码", page, pageSize);
        setPage(page)
        setPageSize(pageSize)
      }


      const rowSelection = {
        onChange: (key: any, row: DataType[]) => {
    
          let checkArr: any = [];
          row.map((item) => {
            checkArr.push(item.skuId)
          })
          setSelectedRow(checkArr)
          console.log("checkArr",checkArr);
          
        },
      }

    // 点击删除
    const { confirm } = Modal;
  
const delSku =(record:any)=>{

    confirm({
        centered: true,
        cancelText: "取消",
        okText: "确定",
        title: '是否删除',
        icon: <ExclamationCircleFilled />,
        content: '',
        onOk() {
            deleteSku({id:record.skuId}).then((res)=>{
                console.log(res.msg);
                goodsList({
                    "limit": pageSize,
                    "page": page
                  })
            })
          console.log('OK');
        },
        onCancel() {
          console.log('Cancel');
        },
      });


   
}

    

    //  点击添加，弹出弹框
    const [type, setType] = useState<string>('')
    const [isModalOpen, setIsModalOpen] = useState<boolean>(false); // 对话框是否打开
    const clickAdd = () => {
        if (selectedRow.length > 0) {
            setType("add")
            setIsModalOpen(true)
        } else {
            message.warning('请至少选择一项')
        }

    }




    // 点击修改，传递值
    const [modStuInfo, setModStuInfo] = useState<DataType>()
   
    // 点击取消
    const close = () => {
        setIsModalOpen(false)
    }
     //按是否上架搜索内容
  const handleChange2 = (value: string) => {
    console.log(`按是否上架搜索 ${value}`);
    getListByCon({
        "limit": pageSize,
        "num": value,
        "page": page
      }).then((res) => {
        console.log(res.msg, res.data);
        setData(res.data.skuVos)
        addKey(res.data.skuVos)
        setCount(res.data.total)
      })

  };


    return (
        <div className='Tag'>
            {/* 头部 */}
            <div className='page-top'>
                {/*左边标题  */}
                <div className='page-title'>
                    <p>库存设置</p>
                </div>
            </div>

            {/* 内容区 */}
            <div className='page-context'>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='list-title'>
                        <p>数据列表</p>
                        <div className='list-operation'>
                            <div className='stockMethod'>
                                <span style={{ marginRight: "15px" }}>排序方式</span>
                                <Select
                                    dropdownStyle={{ width: '120px' }}
                                    className='Select1'
                                    defaultValue="排序方式"
                                    onChange={handleChange2}
                                    options={sort}
                                />
                            </div>
                            <button className='add detals' onClick={clickAdd}>批量修改</button>
                        </div>
                    </div>

                    {/* 表格部分 */}
                    <ConfigProvider locale={zh_CN}>
                        <Table
                            rowSelection={rowSelection}
                            columns={columns}
                            dataSource={data}
                            scroll={{ y: 444 }}
                           rowKey={item => String(item.id)}
                            pagination={{
                                position: ['bottomCenter'],
                                total: count,
                                defaultPageSize: 5,
                                pageSizeOptions: [3, 5, 10, 15],
                                showQuickJumper: true,
                                showSizeChanger: true,
                                onChange: onChangePage
                            }}
                        />
                    </ConfigProvider>


                </div>

            </div>

            {/* 弹框 */}
            <TagDialog page={page} pageSize={pageSize}  goodsList={goodsList} selectedRow={selectedRow} isModalOpen={isModalOpen} modStuInfo={modStuInfo} type={type} close={close}></TagDialog>
                  
        </div>
    )
}

export default GoodStock